package com.zdoon.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zdoon.mapper.StudentMapper;
import com.zdoon.pojo.PageResult;
import com.zdoon.pojo.Student;
import com.zdoon.pojo.StudentQueryParam;
import com.zdoon.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    private static final Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        //        设置pageHelper
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
//        查询数据
        List<Student> studentList = studentMapper.selectStudentList(studentQueryParam);
//        封装数据
        Page<Student> studentPage = (Page<Student>) studentList;

        PageResult<Student> studentPageResult = new PageResult<>(studentPage.getTotal(), studentPage.getResult());

        return studentPageResult;
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    @Override
    public void add(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.add(student);
    }

    @Override
    public Student getById(Integer id) {
        Student student = studentMapper.getById(id);
        return student;
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateViolation(Integer id, Integer score) {
//        查询当前学生的违规次数和违规分数
        Student student = studentMapper.selectViolation(id);
//        获取当前学生的违规次数和违规分数
        Short violationCount = student.getViolationCount();
        Short violationScore = student.getViolationScore();

        violationCount = (short) (violationCount + 1);
        violationScore = (short) (violationScore + score);

        LocalDateTime updateTime = LocalDateTime.now();

        log.info("更新学生信息，参数：{}", student);

        studentMapper.updateViolation(id, violationCount, violationScore, updateTime);
    }
}
